package com.niiwoo.civet.trade.service.local.newRefund.notify.dubbo;

import java.math.BigDecimal;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.niiwoo.civet.base.enums.RefundTypeEnum;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.entity.ProjectBorrowerSummary;
import com.niiwoo.civet.trade.dao.mapper.ProjectBorrowerSummaryMapperExt;
import com.niiwoo.civet.trade.dto.ProjectRepayTotalAmountDTO;
import com.niiwoo.civet.trade.service.local.newRefund.common.RefundCommonService;
import com.niiwoo.civet.trade.service.local.newRefund.notify.RefundNotifyHandle;
import com.niiwoo.civet.trade.service.local.newRefund.notify.dto.RefundNotifyDTO;
import com.niiwoo.civet.trade.service.local.newRefund.notify.dto.RefundNotifyHandleResult;
import com.niiwoo.civet.trade.service.local.newRefund.notify.enums.RefundNotifyEnum;
import com.niiwoo.civet.trade.service.local.newRefund.refundDeal.core.FeeCalcForRefundService;
import com.niiwoo.civet.trade.service.local.refund.CommonLocalService;
import com.niiwoo.civet.trade.utils.RepaymentUtil;
import com.niiwoo.tripod.tiancheng.component.TianChengRefundEventService;
import com.niiwoo.tripod.tiancheng.request.df.ProjectOverdueEventRequest;
import com.niiwoo.tripod.tiancheng.response.common.TianchengUapResponse;

import lombok.extern.slf4j.Slf4j;

/**
 * 天称-标的逾期数据回流
 * 
 * 触发条件：标的逾期
 *
 * @author: kevin.jia
 * @version 1.0.0
 */
@Slf4j
@Service
public class TianChengProjectOverdueNotify implements RefundNotifyHandle {
	
	@Autowired
	private ProjectBorrowerSummaryMapperExt projectBorrowerSummaryMapper;
	
	@Autowired
	private FeeCalcForRefundService feeCalcForRefundService;
	
	@Autowired
	private RefundCommonService refundCommonService;
	
	@Autowired
	private CommonLocalService commonLocalService;
	
	@Autowired
	private TianChengRefundEventService tianChengRefundEventService;
	
	@Override
	public RefundNotifyHandleResult handle(RefundNotifyDTO refundNotifyDTO) {
		RefundNotifyHandleResult refundNotifyHandleResult = null;
		try {
			ProjectOverdueEventRequest projectOverdueEventRequest = (ProjectOverdueEventRequest) bulidParam(refundNotifyDTO);
			
			log.info("天称-标的逾期数据回流 ，ProjectId：{}， 请求参数：{}", refundNotifyDTO.getProject().getProjectId(), JSONObject.toJSONString(projectOverdueEventRequest));
			CompletableFuture<TianchengUapResponse> completableFuture = tianChengRefundEventService.projectOverdue(projectOverdueEventRequest);
			TianchengUapResponse tianchengUapResponse = completableFuture.get(3, TimeUnit.SECONDS);
			log.info("天称-标的逾期数据回流 ，ProjectId：{}， 返回结果：{}", refundNotifyDTO.getProject().getProjectId(), JSONObject.toJSONString(tianchengUapResponse));
			refundNotifyHandleResult = new RefundNotifyHandleResult();
		} catch (Exception e) {
			refundNotifyHandleResult = new RefundNotifyHandleResult(e.getMessage());
			log.error("天称-标的逾期数据回流，异常原因：{}， 请求参数：{}", e.getMessage(), JSONObject.toJSONString(refundNotifyDTO.getRefundNotifyRecord()), e);
		}
		return refundNotifyHandleResult;
	}

	@Override
	public Object bulidParam(RefundNotifyDTO refundNotifyDTO) {
        Project project = refundNotifyDTO.getProject();
        ProjectBorrowerSummary summary = projectBorrowerSummaryMapper.selectByPrimaryKey(refundNotifyDTO.getProjectId());
        
		// 逾期天数
		int overdueDay = RepaymentUtil.getOverdueDay(summary.getRefundDate(), commonLocalService.getCurrentDate());
        
        // 已还金额
		BigDecimal refundAmount = summary.getRefundedCorpus().add(summary.getRefundedInterest())
				.add(summary.getRefundedManagementFee()).add(summary.getRefundedGuaranteeFee())
				.add(summary.getRefundedPenaltyFee());
		
		// 待还总金额
		ProjectRepayTotalAmountDTO toRepayTotalAmountDTO = refundCommonService.getProjectTotalNeedRepayAmount(project.getProjectId(), project.getBorrowUserId());
        
		// 计算待还金额
        BigDecimal repayAmount = feeCalcForRefundService.caculateAmountRepaymentForAPP(project.getProjectId(), RefundTypeEnum.IMMEDIATELY).getAmount();
        
		ProjectOverdueEventRequest projectOverdueEventRequest = new ProjectOverdueEventRequest();
		projectOverdueEventRequest.setUserId(project.getBorrowUserId());
		projectOverdueEventRequest.setProjectId(project.getProjectId());
		projectOverdueEventRequest.setType(project.getSubStatus());
		projectOverdueEventRequest.setDays(overdueDay);
		projectOverdueEventRequest.setYhAmount(repayAmount); // 当前应还
		projectOverdueEventRequest.setDoneAmount(refundAmount); // 已还金额
		projectOverdueEventRequest.setUnpaidAmount(toRepayTotalAmountDTO.getTotalAmount()); // 未还金额
        
        return projectOverdueEventRequest;
	}

	@Override
	public RefundNotifyEnum getType() {
		return RefundNotifyEnum.TIANCHENG_PROJECT_OVERDUE;
	}	
}